package com.yjha.lzmarathonsys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjha.lzmarathonsys.bean.TbSpecialClockin;
import com.yjha.lzmarathonsys.bean.TbUser;
import com.yjha.lzmarathonsys.dto.Param;
import com.yjha.lzmarathonsys.mapper.TbUserMapper;
import com.yjha.lzmarathonsys.service.TbUserService;
import com.yjha.lzmarathonsys.utils.PageUtils;
import com.yjha.lzmarathonsys.utils.PasswordUtil;
import com.yjha.lzmarathonsys.utils.Query;
import com.yjha.lzmarathonsys.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {
    @Override
    public R register(TbUser user) {
        // 必填项非空校验
        if (StrUtil.hasBlank(user.getUseraccount(), user.getPassword())) {
            return R.error("必填项不能为空");
        }

        // 账号唯一性校验
        if (this.count(new QueryWrapper<TbUser>().eq("useraccount", user.getUseraccount())) > 0) {
            return R.error("账号已被注册");
        }

        // 手机号格式校验（简单示例）
        if (!user.getPhone().matches("^1[3-9]\\d{9}$")) {
            return R.error("手机号格式错误");
        }

        String  salt = UUID.randomUUID().toString();
        user.setSalt(salt);

        // ---------- 密码加密 ----------
        String encryption = PasswordUtil.encryption(user.getPassword(), salt, 3);
        user.setPassword(encryption);

        // ---------- 写入数据库 ----------
        boolean success = this.save(user);
        if (!success) {
            return R.error("注册失败，请重试");
        }

        return R.ok("注册成功");
    }

    @Override
    public PageUtils queryPage(TbUser user) {
        Map<String, Object> param = new HashMap<>();
        String page1 = user.getPage();
        String limit1 = user.getLimit();
        param.put("page", page1);
        param.put("limit", limit1);
        QueryWrapper<TbUser> tbUserQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(user.getUseraccount())){
            param.put("useraccount", user.getUseraccount());
        }
        if(!StringUtils.isEmpty(user.getUsername())){
            tbUserQueryWrapper.like("username", "%"+user.getUsername()+"%");
        }

        if(!StringUtils.isEmpty(user.getPhone())){
            tbUserQueryWrapper.like("phone", user.getPhone()+"%");
        }
        IPage<TbUser> page = this.page(
                new Query<TbUser>().getPage(param),
                tbUserQueryWrapper.orderByDesc("id")
        );

        for (TbUser record : page.getRecords()) {
            record.setPassword(null);
            record.setSalt(null);
        }
        return new PageUtils(page);
    }
}
